package com.bingxue.edu.framework.mybatis.listener;

import cn.hutool.core.util.ObjectUtil;
import com.bingxue.edu.framework.common.model.AuditableEntity;
import com.bingxue.edu.management.auth.EmployeeAuthUtil;
import com.mybatisflex.annotation.InsertListener;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @author panbo
 * @since 2024/6/28
 */
@Slf4j
public class AuditingInsertListener implements InsertListener {
    @Override
    public void onInsert(Object o) {
        try {
            if (ObjectUtil.isNotNull(o) && o instanceof AuditableEntity entity) {
                LocalDateTime now = LocalDateTime.now();
                entity.setCreateTime(entity.getCreateTime() == null ? now : entity.getCreateTime());
                entity.setUpdateTime(entity.getUpdateTime() == null ? now : entity.getUpdateTime());

                String userId = entity.getCreateUser() == null ? EmployeeAuthUtil.getCurrentUserId() : entity.getCreateUser();
                entity.setCreateUser(userId);
                entity.setUpdateUser(userId);
            }
        } catch (Exception e) {
            log.warn("自动注入异常，{}", e.getMessage());
        }
    }
}
